package com.learn.springboot3.controller;


import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.springboot3.pojo.LogsBean;
import com.learn.springboot3.pojo.PanelLog;
import com.learn.springboot3.pojo.Sshd;
import com.learn.springboot3.pojo.Url;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName: PanelController
 * Package: com.learn.springboot3.controller
 * Description:
 *
 * @Author jiangCheng
 * @Create 2024/10/12 11:19
 * @Version 1.0
 */

@RestController
@RequestMapping("1pael")
public class PanelController {
    ExecutorService executorService = Executors.newFixedThreadPool(4);
    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping("ssh/{key}")
    public String getSsh(@PathVariable("key") String key) throws IOException, ParseException {
        return redisTemplate.opsForValue().get(key)+"%";
    }
    @PostMapping("ssh")
    public String test(@RequestBody Url url) throws IOException, ParseException {
        long l = System.currentTimeMillis();
        int page =1;
        int pageSize = 10;
        String json = "{"
                + "    \"status\": \"All\","
                + "    \"page\": "+page+","
                + "    \"pageSize\": "+pageSize
                + "}";
        String result = post(url.getUrl(), json, url.getCookie());
        ObjectMapper mapper = new ObjectMapper();
        PanelLog panelLog = mapper.readValue(result, PanelLog.class);
        String key =MD5.create().digestHex(url.getUrl());
        int totalCount = panelLog.getData().getTotalCount();
        pageSize =100;
        for (int i = 0; i <=totalCount/pageSize; i++) {
            json ="{"
                    + "    \"status\": \"All\","
                    + "    \"page\": "+(i+1)+","
                    + "    \"pageSize\": "+pageSize
                    + "}";
            System.out.println("开始处理第几页+"+(i+1));
            //天花板


            double i1 = (double)(i + 1) /  Math.ceil((totalCount / (double)pageSize));


            redisTemplate.opsForValue().set( key,Double.toString(i1*100));
            result = post(url.getUrl(), json, url.getCookie());
            ObjectMapper mapper1 = new ObjectMapper();
            PanelLog panelLog1 = mapper1.readValue(result, PanelLog.class);
            List<LogsBean> logs1 = panelLog1.getData().getLogs();
            for (LogsBean log : logs1) {
                if ("Failed".equals(log.getStatus())){
                    redisTemplate.opsForSet().add(url.getUrl(),log.getAddress());
                }
            }
        }
        System.out.println(result);
        long l2 = System.currentTimeMillis();

        System.out.println("l2 -l = " + (l2 -l));
        return "ok";
    }


    @PostMapping("amqp")
    public String amqp(@RequestBody Url url) throws IOException {
        int page =1;
        int pageSize = 10;
        String json = "{"
                + "    \"status\": \"All\","
                + "    \"page\": "+page+","
                + "    \"pageSize\": "+pageSize
                + "}";
        String result = null;
        String s = MD5.create().digestHex(url.getUrl());
        try {
            result = post(url.getUrl(), json, url.getCookie());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        ObjectMapper mapper = new ObjectMapper();
        PanelLog panelLog = mapper.readValue(result, PanelLog.class);
        int totalCount = panelLog.getData().getTotalCount();
        return "您的总数据量为:"+totalCount + "\n" +
                "数据进度查询处理网址："+"localhost:8090/1pael/ssh/"+s+"\n"
                + "数据处理限制为1天一次";
    }

    public static String post(String url, String jsonBody,String cookie) throws IOException, ParseException {
        String result = null;
        org.apache.hc.client5.http.classic.methods.HttpPost post = new org.apache.hc.client5.http.classic.methods.HttpPost(url);
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Accept", "application/json, text/plain, */*");
        post.setHeader("Cookie", cookie);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0");
        post.setEntity(new StringEntity(jsonBody));
       CloseableHttpClient httpclient = HttpClients.createDefault();
           CloseableHttpResponse response = httpclient.execute(post);
                // 获取响应信息
                result = EntityUtils.toString(response.getEntity());
        return result;
    }

    @PostMapping("sshThead")
    public String sshThead(@RequestBody Url url) throws IOException, ParseException {
        long l = System.currentTimeMillis();
        int page =1;
        int pageSize = 10;
        String json = "{"
                + "    \"status\": \"All\","
                + "    \"page\": "+page+","
                + "    \"pageSize\": "+pageSize
                + "}";
        String result = post(url.getUrl(), json, url.getCookie());
        ObjectMapper mapper = new ObjectMapper();
        PanelLog panelLog = mapper.readValue(result, PanelLog.class);

        int totalCount = panelLog.getData().getTotalCount();
        pageSize =100;
        int finalPageSize = pageSize;
        Runnable task1 = () -> {
            for (int i = 1; i <=14; i++) {
               String  jsona ="{"
                        + "    \"status\": \"All\","
                        + "    \"page\": "+(i+1)+","
                        + "    \"pageSize\": "+ finalPageSize
                        + "}";
                System.out.println("开始处理第几页+"+(i+1));
                Double i1 = (double)(i + 1) / (totalCount / finalPageSize);
                redisTemplate.opsForValue().set("e72e1f06875ab8abf6fc617b60aa2d941",Double.toString(i1*100));
                String a = null;
                try {
                    a = post(url.getUrl(), jsona, url.getCookie());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                ObjectMapper mapper1 = new ObjectMapper();
                PanelLog panelLog1 = null;
                try {
                    panelLog1 = mapper1.readValue(a, PanelLog.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                List<LogsBean> logs1 = panelLog1.getData().getLogs();
                for (LogsBean log : logs1) {
                    if (log.getStatus().equals("Failed")){
                        redisTemplate.opsForSet().add(url.getUrl(),log.getAddress());
                    }
                }
            }
        };

        executorService.submit(task1);

        Runnable task2 = () -> {
            for (int i = 15; i <=30; i++) {
                String  jsona ="{"
                        + "    \"status\": \"All\","
                        + "    \"page\": "+(i+1)+","
                        + "    \"pageSize\": "+ finalPageSize
                        + "}";
                System.out.println("开始处理第几页+"+(i+1));
                Double i1 = (double)(i + 1) / (totalCount / finalPageSize);
                redisTemplate.opsForValue().set("e72e1f06875ab8abf6fc617b60aa2d941",Double.toString(i1*100));
                String a = null;
                try {
                    a = post(url.getUrl(), jsona, url.getCookie());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                ObjectMapper mapper1 = new ObjectMapper();
                PanelLog panelLog1 = null;
                try {
                    panelLog1 = mapper1.readValue(a, PanelLog.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                List<LogsBean> logs1 = panelLog1.getData().getLogs();
                for (LogsBean log : logs1) {
                    if (log.getStatus().equals("Failed")){
                        redisTemplate.opsForSet().add(url.getUrl(),log.getAddress());
                    }
                }
            }
        };

        executorService.submit(task2);

        for (int i = 31; i <=totalCount/pageSize; i++) {
            json ="{"
                    + "    \"status\": \"All\","
                    + "    \"page\": "+(i+1)+","
                    + "    \"pageSize\": "+pageSize
                    + "}";
            System.out.println("开始处理第几页+"+(i+1));
            Double i1 = (double)(i + 1) / (totalCount / pageSize);
            redisTemplate.opsForValue().set("e72e1f06875ab8abf6fc617b60aa2d942",Double.toString(i1*100));
            result = post(url.getUrl(), json, url.getCookie());
            ObjectMapper mapper1 = new ObjectMapper();
            PanelLog panelLog1 = mapper1.readValue(result, PanelLog.class);
            List<LogsBean> logs1 = panelLog1.getData().getLogs();
            for (LogsBean log : logs1) {
                if (log.getStatus().equals("Failed")){
                    redisTemplate.opsForSet().add(url.getUrl(),log.getAddress());
                }
            }
        }
        System.out.println(result);
        long l2 = System.currentTimeMillis();

        System.out.println("l2 -l = " + (l2 -l));
        return "ok";
    }


    @PostMapping("sshd")
    public String sshd(@RequestBody Url url) throws IOException, ParseException {
        Set<String> members = redisTemplate.opsForSet().members(url.getUrl());
        if (ObjectUtils.isEmpty(members)){
            return "无可禁用ip";
        }
        String[] array = members.stream().toArray(String[]::new);
        Sshd sshd = new Sshd();
        sshd.setIps(array);
        sshd.setOperate("banned");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(sshd);
      post(url.getJson(),json, url.getCookie());
        return json;
    }
}
